<?php
class Model_DbToXml extends Model_Base
{
	const DB_AS_XML_ROOT_DIR = 'HackerU/DbAsXml';
	
	public function __construct()
	{
		if(!is_dir(self::DB_AS_XML_ROOT_DIR)){
			mkdir(self::DB_AS_XML_ROOT_DIR);
		}
	}
	
	public function export()
	{
		$tablesName = array(
			'users',
			'tests'
		);
		$modelTableNamePrefix = 'Model_DbTable_';
		foreach ($tablesName as $tableName){
			$modelTableName = $modelTableNamePrefix.ucfirst($tableName);
			$dbTable = new $modelTableName();
			$results = $dbTable->fetchAll();
			$this->saveXml($tableName, $results);
		}
	}
	
	private function saveXml($tableName, array $tableData)
	{
		$xmlFileName = self::DB_AS_XML_ROOT_DIR.'/'.$tableName.'.xml';
		$dom = new DOMDocument('1.0', 'utf-8');
		$dom->formatOutput = true;
		$root = $dom->createElement($tableName);
		$elementName = substr($tableName, 0, strlen($tableName)-1);
		foreach ($tableData as $row){
			$elementNameObj = $dom->createElement($elementName);
			$row = (array)$row;
			foreach ($row as $nodeName => $nodeVal){
				$node = $dom->createElement($nodeName, $nodeVal);
				$elementNameObj->appendChild($node);
			}
			$root->appendChild($elementNameObj);
		}
		
		$dom->appendChild($root);
		$dom->save($xmlFileName);
	}
	
}